package tmproject.hlhj.fhp.cartrans.activitys

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Message
import android.support.v7.app.AlertDialog
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.aty_class_detail.*
import tmproject.hlhj.fhp.cartrans.BaseAty
import tmproject.hlhj.fhp.cartrans.IView.ClassDetailView
import tmproject.hlhj.fhp.cartrans.R
import tmproject.hlhj.fhp.cartrans.fragments.LearnFragment
import tmproject.hlhj.fhp.cartrans.http.NumUtil
import tmproject.hlhj.fhp.cartrans.utils.TimeUtils
import tmproject.hlhj.fhp.cartrans.javaBean.ClassDetailBean
import tmproject.hlhj.fhp.cartrans.javaBean.SaveClassBean
import tmproject.hlhj.fhp.cartrans.presenter.ClassDetailPresenter
import tmproject.hlhj.fhp.cartrans.utils.SpHelper
import tmproject.hlhj.fhp.cartrans.utils.ToastUtils

/**
 * Created by Never Fear   on 2018\8\28 0028.
Never More....
 */
class ClassDetailAty :BaseAty<ClassDetailView,ClassDetailPresenter>(), ClassDetailView {
//    private var url="https://www.bilibili.com/video/av1793716/"
    private var alreadyTime=0//学习时间 sec
    private var tempTime=0
    private var cid=-1
    private var needTime=0
    private var hasSave=false
    private val handler= @SuppressLint("HandlerLeak")

    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (alreadyTime<needTime){
                alreadyTime++
                this.sendEmptyMessageDelayed(1,1000)
            }else{
                ToastUtils.toast("已完成学习")
                presenter?.saveClass(cid,SpHelper.getToken(this@ClassDetailAty),NumUtil.formatNum(((alreadyTime-tempTime)/60f),2)!!,this@ClassDetailAty)

            }
            invidView()
        }


    }
    override fun bindView(): ClassDetailView {
        return this
    }

    override fun createPresenter(): ClassDetailPresenter {

        return ClassDetailPresenter()
    }

    override fun getContentId(): Int {
        return R.layout.aty_class_detail
    }

    @SuppressLint("WrongConstant")
    override fun initView() {
        cid=intent.getIntExtra("id",-1)

        tvMonth.text="本月已学习 ${LearnFragment.alreadyTime}分钟"
        initWeb()
//        webView.loadUrl(url)
    }

    @SuppressLint("WrongConstant")
    private fun initWeb() {
        val webSettings = webView.getSettings()
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setCacheMode(1)
        }

        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true)
        } else {
            webSettings.setLoadsImagesAutomatically(false)
        }

        if (Build.VERSION.SDK_INT >= 11) {
            webView.setLayerType(1, null as Paint?)
        }

        webView.setLayerType(2, null as Paint?)
        webSettings.setJavaScriptEnabled(true)
        webSettings.setSupportZoom(true)
        webSettings.setBuiltInZoomControls(true)
        webSettings.setDisplayZoomControls(false)
//        webSettings.setUseWideViewPort(true)
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN)
        webSettings.setLoadWithOverviewMode(true)
        webSettings.setDatabaseEnabled(true)
        webSettings.setSavePassword(true)
        webSettings.setDomStorageEnabled(true)
        webView.setSaveEnabled(true)
        webView.setKeepScreenOn(true)
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (!url.startsWith("http:") && !url.startsWith("https:")) {
                    try {
                        val intent = Intent("android.intent.action.VIEW", Uri.parse(url))
                        startActivity(intent)
                        return true
                    } catch (e: Exception) {

                    } finally {
                        return true
                    }
                } else {
                    view.loadUrl(url)
                    return false
                }
            }
        }
    }

    override fun logicStart() {
        presenter?.getClassDetail(cid,SpHelper.getToken(this),this)
    }

    override fun setDetailData(classDetailBean: ClassDetailBean) {
        tvTittle.text=classDetailBean.data.title
        alreadyTime=(classDetailBean.data.learned_time*60f).toInt()
        tempTime=(classDetailBean.data.learned_time*60f).toInt()
        needTime=(classDetailBean.data.required_time*60).toInt()
        webView.loadDataWithBaseURL(null,classDetailBean.data.content,"text/html", "utf-8",null)

        invidView()
        handler.sendEmptyMessage(1)
    }

    override fun onDestroy() {
        handler.removeMessages(1)
        super.onDestroy()
    }
    override fun setSaveClassResult(saveClassBean: SaveClassBean) {
        finish()
    }
    private fun invidView(){
        tvAlready.text="已学习:${TimeUtils.secToTime(alreadyTime)}"
        needtime.text="${TimeUtils.secToTime(needTime)}"
        val progressNum = ((alreadyTime.toFloat() / needTime.toFloat()) * 100).toInt()
        progress.progress = progressNum

    }

    override fun onBackPressed() {
//        super.onBackPressed()
        btExit.performClick()
    }
    override fun setListener() {
        btExit.setOnClickListener {
            if (!hasSave){
                AlertDialog.Builder(this)
                        .setTitle("!!!您还未保存学习")
                        .setMessage("请保存学习后再退出")
                        .setPositiveButton("好的"){
                            dialogInterface, i ->
                            dialogInterface.dismiss()
                        }
                        .show()
            }else{
                finish()
            }
        }
        btSave.setOnClickListener {
            presenter?.saveClass(cid,SpHelper.getToken(this@ClassDetailAty),NumUtil.formatNum(((alreadyTime-tempTime)/60f),2)!!,this@ClassDetailAty)
        }
    }
}